package com.app.medicalcontrol.home;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.IdRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;
import android.widget.RadioGroup;
import com.app.medicalcontrol.R;
import com.app.medicalcontrol.basis.BaseMainFragment;
import com.app.medicalcontrol.basis.BasisActivity;
import com.app.medicalcontrol.basis.Constants;
import com.app.medicalcontrol.bean.LoginBean;
import com.app.medicalcontrol.event.RobotListRefreshEvent;
import com.app.medicalcontrol.event.WebReLoadEvent;
import com.app.medicalcontrol.fragment.Robot.RobotFragment;
import com.app.medicalcontrol.fragment.User.child.UserCenterFragment;
import com.app.medicalcontrol.fragment.WebViewX5Fragment;
import com.flyco.dialog.listener.OnBtnClickL;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
import butterknife.OnClick;
import my.CheckPermissionUtils;
import my.DialogUtils;

/**
 * @作者 suncco
 * @备注 首页的TabActivity ，作为容器装载各个页面activity
 */
@SuppressWarnings("deprecation")
public class HomeTabActivity extends BasisActivity implements RadioGroup.OnCheckedChangeListener, BaseMainFragment.OnBackToFirstListener{

    private RadioGroup mRadioGroup;
    private FrameLayout mLayout;

    private FragmentManager fragmentManager;
    private static final String CURRENT_FRAGMENT = "STATE_FRAGMENT_SHOW";
    private Fragment currentFragment = new Fragment();

    private List<Fragment> fragments = new ArrayList<>();
    private int currentIndex = 0;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.base_tab_activity);

        mRadioGroup= (RadioGroup) findViewById(R.id.rg_radio_navigation);
        mRadioGroup.setOnCheckedChangeListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        //初始化权限
        initPermission();
        fragmentManager =getSupportFragmentManager();
        if (savedInstanceState != null) { // “内存重启”时调用
            //获取“内存重启”时保存的索引下标
            currentIndex = savedInstanceState.getInt(CURRENT_FRAGMENT,0);
            //注意，添加顺序要跟下面添加的顺序一样！！！！
            fragments.removeAll(fragments);
            fragments.add(fragmentManager.findFragmentByTag(0+""));
            fragments.add(fragmentManager.findFragmentByTag(1+""));
            fragments.add(fragmentManager.findFragmentByTag(2+""));
            fragments.add(fragmentManager.findFragmentByTag(3+""));
            fragments.add(fragmentManager.findFragmentByTag(4+""));
            //恢复fragment页面
            restoreFragment();
        }else{      //正常启动时调用
            fragments.add(new RobotFragment());
            fragments.add(WebViewX5Fragment.getInstance(Constants.H5_MEMBER + LoginBean.getInstance().getToken().getValue(),"会员服务"));
            fragments.add(WebViewX5Fragment.getInstance(Constants.H5_PAKAGE + LoginBean.getInstance().getToken().getValue()+"&store_id="+ LoginBean.getInstance().getStore_id(),"艾灸套餐"));
            fragments.add(WebViewX5Fragment.getInstance(Constants.H5_SERVICE+LoginBean.getInstance().getStore_id(),"服务记录"));
            fragments.add(new UserCenterFragment());
            showFragment();
        }
    }

    /**
     * 初始化权限事件
     */
    private void initPermission() {
        //检查权限
        String[] permissions = CheckPermissionUtils.checkPermission(this);
        if (permissions.length == 0) {
            //权限都申请了
            //是否登录
        } else {
            //申请权限
            ActivityCompat.requestPermissions(this, permissions, 100);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        outState.putInt(CURRENT_FRAGMENT,currentIndex);
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        switch (i) {
            case R.id.rb_first:
                currentIndex = 0;
                break;
            case R.id.rb_second:
                currentIndex = 1;
                break;
            case R.id.rb_third:
                currentIndex = 2;
                break;
            case R.id.rb_fourth:
                currentIndex = 3;
                break;
            case R.id.rb_fifth:
                currentIndex = 4;
                break;
        }
        clickNum = 0;
        showFragment();
    }

    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    private void showFragment(){
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //如果之前没有添加过
        if(!fragments.get(currentIndex).isAdded()){
            int a = currentIndex;
            transaction
                    .hide(currentFragment)
                    .add(R.id.fl_radio_show,fragments.get(currentIndex),""+currentIndex);  //第三个参数为添加当前的fragment时绑定一个tag
        }else{
            transaction
                    .hide(currentFragment)
                    .show(fragments.get(currentIndex));
        }
        currentFragment = fragments.get(currentIndex);
        transaction.commit();
        return;
    }

    /**
     * 恢复fragment
     */
    private void restoreFragment(){
        FragmentTransaction mBeginTreansaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            if(i == currentIndex){
                mBeginTreansaction.show(fragments.get(i));
            }else{
                mBeginTreansaction.hide(fragments.get(i));
            }
        }
        mBeginTreansaction.commit();
        //把当前显示的fragment记录下来
        currentFragment = fragments.get(currentIndex);
    }


    @Override
    public void onBackToFirstFragment() {
            DialogUtils.DialogTwo(mContext, "", getString(R.string.sure_now_exit), getString(R.string.now_exit), getString(R.string.app_cancel), new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    finish();
                }
            }, null);
        }

    private  int clickNum = 1;
    @OnClick(R.id.rb_first)
    public void clickFirstBtn(){
//        clickNum++;
//        if(clickNum >1){
//            String a ="456";
//        }
        EventBus.getDefault().post(new RobotListRefreshEvent("刷新界面"));
    }

    @OnClick(R.id.rb_second)
    public void clickSecondBtn(){
        clickNum++;
        if(clickNum >1){
            EventBus.getDefault().post(new WebReLoadEvent("刷新界面"));
        }
    }

    @OnClick(R.id.rb_third)
    public void clickThirdBtn(){
        clickNum++;
        if(clickNum >1){
            EventBus.getDefault().post(new WebReLoadEvent("刷新界面"));
        }
    }

    @OnClick(R.id.rb_fourth)
    public void clickFourthBtn(){
        clickNum++;
        if(clickNum >1){
            EventBus.getDefault().post(new WebReLoadEvent("刷新界面"));
        }
    }

    @OnClick(R.id.rb_fifth)
    public void clickFifthBtn(){
//        clickNum++;
//        if(clickNum >1){
//            String a ="456";
//        }
    }
}


